package com.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bean.User;
import com.service.UserService;

@Controller
@RequestMapping("user")
public class UserAction {
	@Autowired
	private UserService userservice;
	
	/**
	 * 
	 * @param name
	 * @param role
	 * @param model
	 * @return
	 */
	@RequestMapping("toList.do")
	public String toList(String name,Integer role,Model model){
		Map<String, Object> map = new HashMap<String,Object>();
		if(name != null && "".equals(name.trim())){
			name = null;
		}
		map.put("name", name);
		map.put("role", role);
		List<User> list = userservice.selectAllUser(map);
		model.addAttribute("list", list);
		return "users/list";
	}
	
	@RequestMapping("toAdd.do")
	public String toAdd(){
		return "users/add";
	}
	
	@RequestMapping("add.do")
	public String add(User user){
		userservice.insertSelective(user);
		return "redirect:toList.do";
	}
	@RequestMapping("delete.do")
	public String delete(Integer id){
		userservice.deleteById(id);
		return "redirect:toList.do";
	}
	@RequestMapping("toUpdate.do")
	public String toUpdate(Integer id,Model model){
		User user = userservice.selectByPrimaryKey(id);
		model.addAttribute("one", user);
		return "users/update";
	}
	@RequestMapping("update.do")
	public String update(User user){
		userservice.updateByPrimaryKeySelective(user);
		return "redirect:toList.do";
	}
	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}
}
